package io.renren.modules.powercut.service.impl;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import io.renren.modules.powercut.entity.AffectDistrictEntity;
import io.renren.modules.powercut.entity.DistrictEntity;
import io.renren.modules.powercut.entity.bo.StandingbookIndexBo;
import io.renren.modules.powercut.entity.dto.StandingbookDto;
import io.renren.modules.powercut.service.AffectDistrictService;
import io.renren.modules.powercut.service.DistrictService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.powercut.dao.StandingbookDao;
import io.renren.modules.powercut.entity.StandingbookEntity;
import io.renren.modules.powercut.service.StandingbookService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@Service("standingbookService")
public class StandingbookServiceImpl extends ServiceImpl<StandingbookDao, StandingbookEntity> implements StandingbookService {

    @Autowired
    private DistrictService districtService;

    @Autowired
    private AffectDistrictService affectDistrictService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<StandingbookEntity> page = this.page(
                new Query<StandingbookEntity>().getPage(params),
                getQueryWrapper(params)
        );
        return new PageUtils(page);
    }

    @Override
    public StandingbookDto queryStandingbookInfo(String id) {
        StandingbookDto standingbookDto =  baseMapper.selectStandingbookDtoById(id);
        return standingbookDto;
    }

    @Override
    public void exportStandingBook(Map<String, Object> params, HttpServletResponse httpServletResponse) {
        try {
            ServletOutputStream out = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType(".csv");
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode("停电台账.csv","utf-8"));
            ExcelWriter write = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet = new Sheet(1,0, StandingbookIndexBo.class);
            sheet.setSheetName("停电台账");
            write.write(createModelList(params),sheet);
            write.finish();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private List<StandingbookIndexBo> createModelList(Map<String, Object> params) {
        List<StandingbookIndexBo> standingbookIndexBos = new ArrayList<>();
        List<StandingbookEntity> standingbookEntities = this.list(getQueryWrapper(params));
        standingbookEntities.parallelStream().forEach(standingbookEntity -> {
            StandingbookIndexBo standingbookIndexBo = new StandingbookIndexBo();
            BeanUtils.copyProperties(standingbookEntity,standingbookIndexBo);
            standingbookIndexBo.setIsPlan(standingbookEntity.getIsPlan()==0?"非计划内":"计划内");
            standingbookIndexBos.add(standingbookIndexBo);
        });
        return standingbookIndexBos;
    }

    private QueryWrapper<StandingbookEntity> getQueryWrapper(Map<String, Object> params){
        QueryWrapper<StandingbookEntity> entityQueryWrapper = new QueryWrapper<>();
        String company = (String) params.get("company");
        String startTime = (String) params.get("startTime");
        String stopTime = (String) params.get("stopTime");
        String reason = (String)params.get("reason");
        String manager = (String) params.get("manager");
        if(StringUtils.isNotEmpty(company)){
            entityQueryWrapper.eq("company",company);
        }
        if(StringUtils.isNotEmpty(startTime)){
            entityQueryWrapper.apply("date_format(blackout_time,'%Y-%m-%d %H:%i:%s')>=date_format('"+startTime+"','%Y-%m-%d %H:%i:%s')");
        }
        if(StringUtils.isNotEmpty(stopTime)){
            entityQueryWrapper.apply(
                    "date_format(blackout_time,'%Y-%m-%d %H:%i:%s')<=date_format('"+stopTime+"','%Y-%m-%d %H:%i:%s')");
        }
        if(StringUtils.isNotEmpty(reason)){
            entityQueryWrapper.eq("reason",reason);
        }
        if(StringUtils.isNotEmpty(manager)){
            QueryWrapper<DistrictEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("manager",manager);
            List<DistrictEntity> list = districtService.list(queryWrapper);
            List<String> ids = new ArrayList<>();
            list.parallelStream().filter(districtEntity -> districtEntity.getManager().equals(manager)).
                    collect(Collectors.toList()).forEach(districtEntity -> {
                ids.add(districtEntity.getId());
            });
            QueryWrapper<AffectDistrictEntity> affectDistrictEntityQueryWrapper = new QueryWrapper<>();
            affectDistrictEntityQueryWrapper.in("district_id",ids);
            affectDistrictEntityQueryWrapper.select("standingbook_id");
            List<String> standingBookIds = new ArrayList<>();
            List<AffectDistrictEntity> districtEntities = affectDistrictService.list(affectDistrictEntityQueryWrapper);
            districtEntities.forEach(affectDistrictEntity -> {
                standingBookIds.add(affectDistrictEntity.getStandingbookId());
            });
            affectDistrictEntityQueryWrapper.in("id",standingBookIds);
        }
        entityQueryWrapper.orderByDesc("blackout_time");
        return entityQueryWrapper;
    }

}